package cloudLibrary;

import java.util.HashSet;
import java.util.List;

import com.google.appengine.api.datastore.Key;

import javax.jdo.PersistenceManager;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;


@PersistenceCapable
public class Item {

	@PrimaryKey
	@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
	private Key itemID;

	@Persistent
	private String owner;

	@Persistent
	private String title;

	@Persistent
	private String type;

	public Item(String owner, String title, String type) {
		this.owner = owner;
		this.title = title;
		this.type = type;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public Key getItemID() {
		return itemID;
	}

	public void setItemID(Key itemID) {
		this.itemID = itemID;
	}

	public String getOwner() {
		return owner;
	}

	public void setOwner(String owner) {
		this.owner = owner;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public boolean isReserved() {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			String qr = "select from " + Users.class.getName();
			List<Users> users = (List<Users>) pm.newQuery(qr).execute();
			for (Users u : users) {
				HashSet<Key> lended = u.getItems();
				if (lended.contains(this.getItemID()))
					return true;
			}
		} finally {
			pm.close();
		}
		return false;
	}
	public String getBorrower() {
		String resp = "";
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			if (this.isReserved()){
				String query = "select from " + Users.class.getName();
				List<Users> users = (List<Users>) pm.newQuery(query).execute();
				for (Users u : users) {
					if (u.getItems().contains(this.itemID))
						resp = u.getName();
				}
			}
		}
		finally {
			pm.close();
		}
		return (resp);
	}

}
